import { getRandomCode, LoadLogin, submitEditorPwd } from "@/apis/login";
import passwordSvg from "@/assets/login/password.svg";
import { saveToken, setWebId } from "@/common/auth/token";
import { INPUT_MAX_LENGTH, phoneReg, psdRegExp, TEXT_PWD_MSG } from "@/common/constant";
import { Encrypt } from "@/common/encryptHelper";
import { randomUUID } from "@/common/utils";
import { useGlobalContent } from "@/store";
import { SafetyOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Col, Form, Input, Layout, Row } from "antd";
import { useForm } from "antd/es/form/Form";
import { openMessage } from "hy_dev_lib";
import { useEffect, useState } from "react";
import Captcha from "react-captcha-code";
import { ReactSVG } from "react-svg";
import { href } from "../../common/useAxios";
import "./index.less";
import { useGetMenu } from "./useGetMenu";

type Props = {};

const { Header, Content } = Layout;
/** 登录页 */
export default function Login({ }: Props) {
  const { globalDispatch, global } = useGlobalContent();
  const [account, setAccount] = useState<any>(); //账号
  const [pwd, setPwd] = useState<any>(); //密码
  const [checkCode, setCheckCode] = useState<string>(); //输入的验证码
  const [isForgetPassword, setIsForgetPassword] = useState(false);
  const [btnYzm, setBtnYzm] = useState("获取验证码");
  const [form] = useForm();
  const phoneNum = Form.useWatch("dh", form);
  const [yzmStart, setYzmStart] = useState(true);

  //自定义计算验证码
  const [verCode, setVerCode] = useState<any>({});
  const { systemInfo = {} as any } = global || {};

  const { getMenuFn, initUserInfo } = useGetMenu(globalDispatch);

  useEffect(() => {
    // 清空global里存的菜单
    globalDispatch({
      type: "MENU_LIST",
      data: null,
    });
    getVerCode();
    preventBack();
  }, []);

  // 获取验证码
  const getVerCode = () => {
    const a = Math.floor(Math.random() * 10);
    const b = Math.floor(Math.random() * 10);
    const c = ["+", "-", "*"][Math.floor(Math.random() * 2)];
    setVerCode({ a, b, c });
  };

  // 禁用浏览器的回退按钮
  const preventBack = () => {
    if (window.history && window.history.pushState) {
      window.history.pushState({ title: "", url: "" }, "", "");
    }
  };

  // 提交表单
  const LoginIn = () => {
    if (!account?.trim()) return openMessage.warning("请输入姓名/手机号/单位账号")
    if (!pwd) return openMessage.warning("请输入密码")
    if (!checkCode?.trim()) return openMessage.warning("请输入验证码")
    let code = eval(`${verCode.a}${verCode.c}${verCode.b}`);
    if (checkCode?.trim() !== code + "") {
      openMessage.warning("验证码错误，请重试！")
      getVerCode();
      setCheckCode("");
      return;
    }
    LoadLogin({
      account: account.trim(),
      pwd: Encrypt(pwd),
      // randomCode: checkCode.trim(),
    })
      .then((reason: any) => {
        const { token } = reason;
        saveToken(token);
        setWebId(randomUUID());
        initUserInfo();
        localStorage.setItem("defaultShowCockpit", "1");
        getMenu();
      })
      .catch((err: any) => {
        getVerCode();
        setCheckCode("");
      });
  };

  // 获取菜单
  const getMenu = async () => {
    await getMenuFn();
    window.location.href = href;
  };

  const EnterLogin = (e: any) => {
    if (e.keyCode == 13) LoginIn();
  };

  //移除readOnly属性
  const removeReadOnly = () => {
    document.getElementById("oldPwd")?.removeAttribute("readonly");
  };

  const removeNewReadOnly = () => {
    document.getElementById("newPwd")?.removeAttribute("readonly");
  };

  /**
   * 验证码获取
   */
  const getYzCode = async () => {
    if (yzmStart) {
      if (phoneNum) {
        setYzmStart(false);
        let data = await getRandomCode(phoneNum);

        if (data?.code == 200) {
          let yzmTime = 60;
          let yzmTimeFun = setInterval(() => {
            if (yzmTime > 0) {
              setBtnYzm(`${yzmTime}s后重新获取`);
              yzmTime--;
            } else {
              setYzmStart(true);
              setBtnYzm(`获取验证码`);
              clearInterval(yzmTimeFun);
            }
          }, 1000);

          openMessage({
            type: "success",
            content: "验证码获取成功",
          });
        } else {
          openMessage({
            type: "error",
            content: "验证码获取失败",
          });
        }
      } else {
        openMessage({
          type: "warning",
          content: "请输入正确的电话号码",
        });
      }
    }
  };

  const submitEditorPwdFun = () => {
    form.validateFields().then(async () => {
      let forgetFormData = form.getFieldsValue();

      if (forgetFormData.mm !== forgetFormData.cfmm) {
        openMessage({
          type: "warning",
          content: "两次密码应该相同!",
        });
      } else {
        let submitData = {
          dh: forgetFormData.dh,
          mm: Encrypt(forgetFormData.mm),
          cfmm: Encrypt(forgetFormData.cfmm),
          sjyzm: forgetFormData.yzm,
        };

        let data = await submitEditorPwd(submitData);
        if (data?.code == 200) {
          openMessage({
            type: "success",
            content: "密码修改成功!!",
          });
          logInNowfun();
        }
      }
    });
  };

  const logInNowfun = () => {
    form.resetFields();
    setIsForgetPassword(false);
  };

  const { dlbjtdz, dlbtdz, bqsy, jsdw, dlylgdz, dlbjtwzdz } = systemInfo || {};

  return (
    <Layout className="size100 login-page" style={{ backgroundImage: `url(${SYSTEM_GLOBAL.fileBaseURL + dlbjtdz})` }}>
      <Header className="header" style={{ backgroundImage: `url(${SYSTEM_GLOBAL.fileBaseURL + dlbtdz})` }}></Header>
      <Content className="login-contain">
        {dlbjtwzdz && <img src={SYSTEM_GLOBAL.fileBaseURL + dlbjtwzdz} className="slogan"></img>}
        {!isForgetPassword ? (
          <div className="login-form">
            <Row className="welcome-login">欢迎登录</Row>
            <Row className="eng-prompt">Please login to access your account.</Row>
            <Row className="login-row">
              <div className="mark-word">用户名</div>
              <Input
                onKeyDown={EnterLogin}
                maxLength={INPUT_MAX_LENGTH}
                value={account}
                onChange={(e) => {
                  setAccount(e.currentTarget.value);
                }}
                placeholder="请输入账号"
                prefix={<UserOutlined className="large" />}
                autoComplete="off"
              ></Input>
            </Row>
            <Row className="login-row">
              <div className="mark-word">密码</div>
              <Input.Password
                onKeyDown={EnterLogin}
                type="password"
                value={pwd}
                onChange={(e) => setPwd(e.currentTarget.value)}
                placeholder="请输入密码"
                prefix={<ReactSVG src={passwordSvg} className="react-svg large"></ReactSVG>}
                autoComplete="off"
              ></Input.Password>
            </Row>
            <Row className="login-row">
              <div className="mark-word">验证码</div>
            </Row>
            <Row className="code-row">
              <Col span={16} style={{ paddingRight: 10 }}>
                <Input
                  onKeyDown={EnterLogin}
                  maxLength={INPUT_MAX_LENGTH}
                  value={checkCode}
                  onChange={(e) => setCheckCode(e.currentTarget.value)}
                  style={{ height: 40, width: "100%" }}
                  placeholder="请输入验证码"
                ></Input>
              </Col>
              <Col span={8}>
                {/* <Captcha charNum={4} onClick={handleClick} code={randomCode} /> */}
                <Captcha
                  code={`${verCode.a}${verCode.c}${verCode.b}=`}
                  onClick={getVerCode}
                  className="captcha"
                  fontSize={28}
                  width={138}
                  height={40}
                  bgColor="#fff"
                />
              </Col>
            </Row>
            <Button onClick={LoginIn} type="primary" className="login-btn">
              立即登录
            </Button>
            {/* 暂时隐藏 */}
            {/* <Row className="forget-pwd" onClick={forgetPwdFun}>
              忘记密码
            </Row> */}
          </div>
        ) : (
          <div className="login-forgetForm">
            <Row className="forgetForm-title">修改密码</Row>
            <Row className="eng-prompt">Please login to access your account.</Row>
            <Form form={form} className="forgetForm" colon={false} layout="vertical" requiredMark={false}>
              <Form.Item
                className="login-row"
                label="手机号"
                name="dh"
                rules={[
                  { required: true, message: "请输入手机号" },
                  {
                    pattern: phoneReg,
                    message: "手机号格式不正确",
                  },
                ]}
              >
                <Input
                  placeholder="请输入手机号"
                  prefix={<UserOutlined className="large" />}
                />
              </Form.Item>
              <Form.Item
                className="login-row"
                label="验证码"
                name="yzm"
                rules={[{ required: true, message: "请输入验证码" }]}
              >
                <Input
                  maxLength={INPUT_MAX_LENGTH}
                  placeholder="请输入验证码"
                  prefix={<SafetyOutlined className="large" />}
                  suffix={
                    <div
                      style={{
                        textDecoration: "underline",
                        color: "#4C70FF",
                        cursor: "pointer",
                      }}
                      onClick={getYzCode}
                    >
                      {btnYzm}
                    </div>
                  }
                />
              </Form.Item>
              <Form.Item
                className="login-row"
                label="密码"
                name="mm"
                rules={[
                  {
                    required: true,
                    pattern: psdRegExp,
                    message: TEXT_PWD_MSG,
                  },
                ]}
              >
                <Input.Password
                  id="oldPwd"
                  type="password"
                  placeholder="请输入密码"
                  prefix={<ReactSVG src={passwordSvg} className="react-svg large"></ReactSVG>}
                  readOnly
                  onFocus={removeReadOnly}
                />
              </Form.Item>
              <Form.Item
                className="login-row"
                label="重复密码"
                name="cfmm"
                rules={[
                  {
                    required: true,
                    pattern: psdRegExp,
                    message: TEXT_PWD_MSG,
                  },
                ]}
              >
                <Input.Password
                  id="newPwd"
                  type="password"
                  placeholder="请再次输入密码"
                  prefix={<ReactSVG src={passwordSvg} className="react-svg large"></ReactSVG>}
                  readOnly
                  onFocus={removeNewReadOnly}
                />
              </Form.Item>
            </Form>
            <Button onClick={submitEditorPwdFun} type="primary" className="forgetPwd-btn">
              确定
            </Button>
            <Row className="forget-pwd" onClick={logInNowfun}>
              立即登录
            </Row>
          </div>
        )}
        <div className="company-msg">
          <img src={SYSTEM_GLOBAL.fileBaseURL + dlylgdz} style={{ height: 40 }}></img>
          <div className="splite"></div>
          <div className="msg">
            <div>技术支持：{jsdw}</div>
            <div>版权所有：{bqsy}</div>
          </div>
        </div>
      </Content>
    </Layout>
  );
}
